﻿using UnityEngine;
using System.Collections;

namespace VoxelBlock
{
    /// <summary>
    /// 自定义的Texture2D数据
    /// </summary>
    public struct MyTexture2D
    {
        public int width;
        public int height;
        public Color32[] colors;
        public MyTexture2D(int a_Width, int a_Height)
        {
            width = a_Width;
            height = a_Height;
            colors = new Color32[a_Width * a_Height];
        }

        public MyTexture2D(Texture2D texture)
        {
            width = texture.width;
            height = texture.width;
            colors = texture.GetPixels32();
        }

        public Texture2D ToTexture2D()
        {
            Texture2D return_MaxTexture2D = new Texture2D(width, height);//, TextureFormat.RGB24, false
            return_MaxTexture2D.filterMode = FilterMode.Point;
            return_MaxTexture2D.wrapMode = TextureWrapMode.Clamp;
            return_MaxTexture2D.mipMapBias = 0f;

            for (int y = 0, i = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++, i++)
                {
                    return_MaxTexture2D.SetPixel(x, y, colors[i]);
                }
            }
            //return_MaxTexture2D.SetPixels32(colors);
            return_MaxTexture2D.Apply();
            return return_MaxTexture2D;
        }

        public Texture2D ToTexture2D(TextureFormat format, FilterMode filterMode, TextureWrapMode wrapMode, float mipMapBias)
        {
            Texture2D return_MaxTexture2D = new Texture2D(width, height, format, false);
            return_MaxTexture2D.filterMode = filterMode;
            return_MaxTexture2D.wrapMode = wrapMode;
            return_MaxTexture2D.mipMapBias = mipMapBias;

            for (int y = 0, i = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++, i++)
                {
                    return_MaxTexture2D.SetPixel(x, y, colors[i]);
                }
            }
            //return_MaxTexture2D.SetPixels32(colors);
            return_MaxTexture2D.Apply();
            return return_MaxTexture2D;
        }


        public Color32[] GetPixels32()
        {
            return colors;
        }


        public void SetPixel(int x, int y, Color32 color)
        {
            try
            {
                this.colors[x + width * y] = color;
            }
            catch (System.Exception)
            {
            }
        }

        public void SetPixels32(Color32[] colors)
        {
            this.colors = colors;
        }
    }
}